package com.nine.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter",urlPatterns = "/*")
public class LoginFilter implements Filter {
    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        // 检查session中是否有用户信息userinfo，若有则放行，反之跳转到登录界面
        HttpServletRequest httpServletRequest = (HttpServletRequest) req;
        HttpServletResponse httpServletResponse = (HttpServletResponse) resp;
        // 获取工程名
        String contextPath = httpServletRequest.getContextPath();
        // 获取session
        HttpSession session = httpServletRequest.getSession();
        // 放行登录界面和登录请求
        String uri = httpServletRequest.getRequestURI();
        if (uri.contains("login") || uri.contains("static")){
            chain.doFilter(req, resp);
        }else {
            if (session.getAttribute("userInfo") != null && !session.getAttribute("userInfo").equals("")) {
                chain.doFilter(req, resp);
            }else {
                httpServletResponse.sendRedirect(contextPath+"/page/loginUser.jsp");
            }
        }
    }

    @Override
    public void init(FilterConfig config) throws ServletException {

    }

}
